<?php

class udnutil
{
    public static function get_country()
    {
        if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'google') !== false)
            return "X";

        $ip = $_SERVER["REMOTE_ADDR"];
        $url = "http://api.ipinfodb.com/v3/ip-country/?key=d22c163297f08622360e651b13b229bbca1b109430a893c438be6e7f045b39e3&format=xml&ip=$ip";
        $xml = file_get_contents($url);

        $xml_data = new DOMDocument();
        @$xml_data->loadXML($xml);
        $domXpath = new DOMXPath($xml_data);

        $items = $domXpath->query("//countryCode");

        if($items->length > 0)
        {
            return $items->item(0)->nodeValue;
        }
        else
            return ".";
    }

    public static function open_connection()
    {
        $con = null;
        include('config.php');
        $con = mysql_connect($db_server, $mysql_username, $mysql_password);
        mysql_select_db($db_name, $con);
        if (!$con)
        {
            die('Could not connect: ' . mysql_error());
        }
        return $con;
    }

    public static function close_connection($con)
    {
        mysql_close($con);
    }

    public static function dlurl($url)
    {
        //http://5.34.247.14/dl/
        //base
        include('config.php');
        return $dl_prefix.base64_encode($url);
    }


    // disguises the curl using fake headers and a fake user agent.
    public static function read_url($url)
    {
        $curl = new Curl();
        $html = $curl->get($url);

        return $html;
    }

    //removes the first match
    public static function removeElement($domxPath, $xpath)
    {
        $domNodeList = $domxPath->query($xpath);
        if ($domNodeList->length > 0) {
            $domNode = $domNodeList->item(0);
            $domNode->parentNode->removeChild($domNode);
        }
    }

    //removes all matches
    public static function removeAllElements($domxPath, $xpath)
    {
        if ($domxPath->query($xpath)->length > 0)
            foreach ($domxPath->query($xpath) as $node)
                $node->parentNode->removeChild($node);
    }

    //replaces the element with a blank one
    public static function blankElement($domxPath, $xpath)
    {
        $domNodeList = $domxPath->query($xpath);
        if ($domNodeList->length > 0) {
            $domNode = $domNodeList->item(0);
            $tag = $domNode->tagName;
            $parent = $domNode->parentNode;
            $parent->removeChild($domNode);
            $parent->appendChild(new DOMElement($tag));
        }
    }

    //replaces the element content with supplied html content
    public static function replaceFirstElement($domxPath, $xpath, $content)
    {
        $domNodeList = $domxPath->query($xpath);

        if ($domNodeList->length > 0) {
            $domNode = $domNodeList->item(0); //this is the element to put content under
            //remove all children before appending the content
            $children = $domNode->childNodes;
            while ($children->length > 0) {
                $domNode->removeChild($children->item(0));
            }
            //append the content after converting to proper format
            $domNode->appendChild(udnutil::getDOMElement($domxPath, $content));
        }
    }


    public static function appendHtmlToTag($domxPath, $xpath, $content)
    {
        $domNodeList = $domxPath->query($xpath);

        if ($domNodeList->length > 0) {
            $domNode = $domNodeList->item(0); //this is the element to put content under
            $domNode->appendChild(udnutil::getDOMElement($domxPath, $content));
        }
    }


    //converts html into domelement so it can be appended somewhere in the same document
    public static function htmlToDOMElement($domXPath, $html)
    {
        $fragment = $domXPath->document->createDocumentFragment();
        $fragment->appendXML($html);
        return $fragment;
        echo $html;
    }

    //sets a all matching elements' attributes to a specific value
    public static function setAttributeValue($domXpath, $xpath, $attribute, $value)
    {
        $domNodeList = $domXpath->query($xpath);
        foreach ($domNodeList as $node) {
            $node->setAttribute($attribute, $value);
        }
    }

    //returns first match domnode
    public static function getNode($domXPath, $xpath, $root = null)
    {
        return udnutil::getAllNodes($domXPath, $xpath, $root)->item(0);
    }

    //returns first match domnode
    public static function getAllNodes($domXPath, $xpath, $root = null)
    {
        if ($root != null)
            $domNodeList = $domXPath->query($xpath, $root);
        else
            $domNodeList = $domXPath->query($xpath);
        return $domNodeList;
    }

    //returns first match value
    public static function getNodeValue($domXPath, $xpath, $root)
    {
        $domNode = udnutil::getNode($domXPath, $xpath, $root);
        return udnutil::clean($domNode->nodeValue);
    }

    public static function get_post_id_by_title($post_title)
    {
        global $wpdb;
        $post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='post'", $post_title));
        if ($post_id)
            return $post_id;
        return null;
    }

    public static function clean($value)
    {
        $value = preg_replace("/[\n\r]/", "", $value);
        $value = htmlspecialchars($value);
        return $value;
    }

    //imdb specific
    public static function scaleImdbImage($image, $multiplier)
    {
        //manipulation of poster size
        $pcs = explode('._V1.', $image);
        $pcs = explode(',', $pcs[1]);

        //_SY##_CR# or _SX##_CR#
        $tmp = explode('_CR', $pcs[0]);
        $sysx = substr($tmp[0], 3); //got the number

        //,"###,
        $num1 = $pcs[2];

        //###_.jpg
        $num2 = str_replace("_.jpg", "", $pcs[3]);

        //imdb default size is 76x113
        //multiply by 2 resulting in (152x226)
        //$multiplier = 2;

        $new_sysx = $sysx * $multiplier;
        $new_num1 = $num1 * $multiplier;
        $new_num2 = $num2 * $multiplier;

        //put the new values back in url (resulting in bigger image size)
        $image = str_replace($sysx . "_CR", $new_sysx . "_CR", $image);
        $image = str_replace("," . $num1 . ",", "," . $new_num1 . ",", $image);
        $image = str_replace("," . $num2 . "_", "," . $new_num2 . "_", $image);
        $image = $image;

        return $image;
    }

    public static function scaleImdbImage2($url, $multiplier)
    {
        $pcs = explode('._V1.', $url);
        preg_match_all('/[0-9]+/', $pcs[1], $matches);
        $count = count($matches[0]);
        for ($i = 0; $i < $count; $i++) {
            $pcs[1] = str_replace($matches[0][$i], $matches[0][$i] * $multiplier, $pcs[1]);
        }
        return $pcs[0] . '._V1.' . $pcs[1];
    }

    public static function originalImdbImage($url)
    {
        $pcs = explode('@@', $url);
        return $pcs[0] . '@@._V1._SY600_SX800.jpg';
    }

    public static function smallImdbImage($url)
    {
        if (strpos($url, '.png') !== false)
            return $url;

        $pcs = explode('._V1.', $url);
        return $pcs[0] . '._V1._SY44_SX44.jpg';
    }

    public static function post_url($url, $params)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        $data = $params;

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $contents = curl_exec($ch);
        //curl_close($ch);

        return $ch;
    }

    public static function getEpisodeTitle($series_name, $season, $episode)
    {
        $series_name = udnutil::clean(htmlspecialchars($series_name));
        //$series_name = str_replace(' ','.',$series_name);

        $snum = strlen($season) < 2 ? '0' . $season : $season;
        $enum = strlen($episode) < 2 ? '0' . $episode : $episode;
        $seasonEpisode = 'S' . $snum . 'E' . $enum;
        return $series_name . ' ' . $seasonEpisode;
    }
    public static function startswith($haystack, $needle)
    {
        return strpos($haystack, $needle) === 0;
    }


    public static function db_check($id, $var, $days_old = 3)
    {
        header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 60*60*24*$days_old));
        date_default_timezone_set("America/Los_Angeles");
        //save to db
        $con = udnutil::open_connection();

        $contents = "";
        $found = false;

        $today = date('Y-m-d H:i:s');
        $result = mysql_query("SELECT DATEDIFF('$today',dt) AS DiffDate, UNCOMPRESS(body) as body1 FROM cache where id='$id'");


        while ($row = mysql_fetch_array($result)) {
            $DiffDate = $row['DiffDate'];

            if ($DiffDate <= $days_old)
            {
                $contents = unserialize($row['body1']);
                $found = true;

                //if cache is available but empty for movie
                if($contents['mode'] == 'movie' && $contents['title'] == " ")
                    $found = false;
            }

        }


        if (!$found) {
            $lang = 'en';
            if(udnutil::startswith($id, 'tt')) // if movie
            {
                //$lang = substr($id,strlen($id)-2);
                //$id= str_replace($lang,"",$id);
                include('movie_parser.php');
                $contents = movie_parser::get_movie($id, $lang, false);
            }
            else if(udnutil::startswith($id, 'nm')) // if person
            {
                //$lang = substr($id,strlen($id)-2);
                //$id= str_replace($lang,"",$id);
                include('person_parser.php');
                $contents = person_parser::get_person($id, $lang, false);

            }
            else if(udnutil::startswith($id, 'home'))
            {
                //$lang = substr($id,strlen($id)-2);
                include('home_parser.php');
                $contents = home_parser::get_home($lang);
            }
            else
            {
                include('search_parser.php');
                $contents = search_parser::get_search($id,$var);
                //$contents = udnutil::read_url($full_url);
            }
            $escaped_contents = mysql_real_escape_string(serialize($contents));
            mysql_query("DELETE FROM cache WHERE id = '$id'");
            mysql_query("INSERT INTO cache (id, body)
          VALUES ('$id', COMPRESS('$escaped_contents'))");
        }

        udnutil::close_connection($con);
        //output

        return $contents;
    }

    public static function fixAccents($string){
        //$string = utf8_decode($string);

        $accents = '/&([A-Za-z]{1,2})(grave|acute|circ|cedil|uml|lig);/';

        $string_encoded = $string;

        //$string_encoded = htmlentities($string,ENT_NOQUOTES,'UTF-8');

        return preg_replace($accents,'$1',$string_encoded);
    }
}

class Curl
{

    public $cookieJar = "";

    public function __construct($cookieJarFile = 'cookies.txt')
    {
        $this->cookieJar = $cookieJarFile;
    }

    function setup()
    {


        $header = array();
        $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Pragma: "; // browsers keep this blank.


        curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($this->curl, CURLOPT_COOKIEJAR, $cookieJar);
        curl_setopt($this->curl, CURLOPT_COOKIEFILE, $cookieJar);
        curl_setopt($this->curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
    }


    function get($url)
    {
        $this->curl = curl_init($url);
        $this->setup();

        return $this->request();
    }

    function getAll($reg, $str)
    {
        preg_match_all($reg, $str, $matches);
        return $matches[1];
    }

    function postForm($url, $fields, $referer = '')
    {
        $this->curl = curl_init($url);
        $this->setup();
        curl_setopt($this->curl, CURLOPT_URL, $url);
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl, CURLOPT_REFERER, $referer);
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);
        return $this->request();
    }

    function getInfo($info)
    {
        $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);
        return $info;
    }

    function request()
    {
        $page = curl_exec($this->curl);
        curl_close($this->curl);

        return $page;
    }


}